<?php
namespace app\oem\controller;
use think\Controller;
use think\Db;
use app\common\controller\OemBaseController;

class Count extends OemBaseController
{
	//统计
     public function summary()
    {
    	$user_level=session("user_level");
		$where = [];
		$map = [];
		if($user_level==1){//oem
			//$where['oem_id']=session('d_id');
			//$map['oem_id']=session('d_id');
		}
		if($user_level==2){//市代理
			$where['agency_id1']=session('d_id');
			$map['agency_id']=session('d_id');
			$bishu_where['agency_id1'] = session("d_id");
			$cz_where['a.agency_id1'] = session('d_id');
		}
		if($user_level==3){//区域运营商
			$where['agency_id2']=session('d_id');
			$bishu_where['agency_id2'] = session("d_id");
			$map['city_id']=session('d_id');
			$cz_where['a.agency_id2'] = session('d_id');
		}
		if($user_level==4){//省代理商
			$map['province_id']=session('d_id');
			$province=db("info_oem")->where($map)->field("id")->select();
			$province_arr=array();
			foreach($province as $val){
				$province_arr[]=$val['id'];
			}
			$province=implode(',',$province_arr);

			$where['agency_id1']=['in',$province];
			$bishu_where['agency_id1'] = ['in',$province];
			$cz_where['a.agency_id1'] = ['in',$province];
		}
		$oemlevel1=db('info_oem')->where($map)->where('user_level',4)->count();		//省代理商
		$oemlevel2=db('info_oem')->where($map)->where('user_level',2)->count();     //市代理商
		$oemlevel3=db('info_oem')->where($map)->where('user_level',3)->count();     //区域运营商
		$mems=db('info_user')->where($where)->count();                              //会员
		$agents=db('info_agent')->where($where)->count();                           //商家
		$sc_where=$where;
		$sc_where['is_pt1']=1;
		$sc=db('info_user')->where($sc_where)->count();                             //市场专员
		$data["oemlevel1"]=$oemlevel1;//省级代理商
		$data["oemlevel2"]=$oemlevel2;//市级代理商
		$data["oemlevel3"]=$oemlevel3;//区域运营商
		$data["mems"]=$mems;          //会员 
		$data["agents"]=$agents;      //商家
		$data["scs"]=$sc;             //市场专员

		$mems=db('info_user')->where($where)->count();
		$today_users=db("info_user")->where($where)->whereTime('add_time', 'today')->cache(60)->count();
	   	$week_users=db("info_user")->where($where)->whereTime('add_time', 'week')->cache(60)->count();
		$month_users=db("info_user")->where($where)->whereTime('add_time', 'month')->cache(60)->count();
		$last_month_users=db("info_user")->where($where)->whereTime('add_time', 'last month')->cache(60)->count();
	    $this->assign('today_mems',$today_users?$today_users:0);
		$this->assign('week_mems',$week_users?$week_users:0);
		$this->assign('month_mems',$month_users?$month_users:0);
		$this->assign('last_month_mems',$last_month_users?$last_month_users:0);
		$this->assign('mems',$mems?$mems:0);
		
		$list=db("log_paylog_copy")->where($where)->field("uid,balance,order_type,score,sy_type,payment_type")->select();
		$logs=db('log_paylog_copy')->where($where)->cache(30)->sum("balance");	   
	   	$today_logs=db("log_paylog_copy")->where($where)->whereTime('add_time', 'today')->cache(30)->sum("balance");
		$week_logs=db("log_paylog_copy")->where($where)->whereTime('add_time', 'week')->cache(30)->sum("balance");
		$month_logs=db("log_paylog_copy")->where($where)->whereTime('add_time', 'month')->cache(30)->sum("balance");
		$last_month_logs=db("log_paylog_copy")->where($where)->whereTime('add_time', 'last month')->cache(30)->sum("balance");
	   	$this->assign("logs",$logs?$logs:0);
	   	$this->assign("today_logs",$today_logs?$today_logs:0);
	   	$this->assign("week_logs",$week_logs?$week_logs:0);
		$this->assign("month_logs",$month_logs?$month_logs:0);
		$this->assign("last_month_logs",$last_month_logs?$last_month_logs:0);

		$bishu_where['order_type'] = ['not in','3,4,5'];
		$bishu_where['state'] = 2;
		
		$counts=db('log_paylog')->where($bishu_where)->cache(30)->count();
	    $today_counts=db("log_paylog")->where($bishu_where)->whereTime('add_time', 'today')->cache(30)->count();
	   	$week_counts=db("log_paylog")->where($bishu_where)->whereTime('add_time', 'week')->cache(30)->count();
		$month_counts=db("log_paylog")->where($bishu_where)->whereTime('add_time', 'month')->cache(30)->count();
		$last_month_counts=db("log_paylog")->where($bishu_where)->whereTime('add_time', 'last month')->cache(30)->count();
	   	$this->assign("counts",$counts?$counts:0);
	   	$this->assign("today_counts",$today_counts?$today_counts:0);
	   	$this->assign("week_counts",$week_counts?$week_counts:0);
		$this->assign("month_counts",$month_counts?$month_counts:0);
		$this->assign("last_month_counts",$last_month_counts?$last_month_counts:0);
		
		$where['balance']=['<',0];
		$where['order_type']=['in','1,3,7'];
//	    $today_scores=db("log_agent_score")->where($where)->whereTime('add_time', 'today')->cache(30)->sum("balance");
//	   	$week_scores=db("log_agent_score")->where($where)->whereTime('add_time', 'week')->cache(30)->sum("balance");
//	   	$month_scores=db("log_agent_score")->where($where)->whereTime('add_time', 'month')->cache(30)->sum("balance");
//	   	$total_scores=db("log_agent_score")->where($where)->cache(30)->sum("balance");
		
		$where1['balance']=['>',0];
		$where1['order_type']=['in','1,3,7'];
	    $today_scores1=db("log_agent_score")->where($where1)->whereTime('add_time', 'today')->cache(30)->sum("balance");
	   	$week_scores1=db("log_agent_score")->where($where1)->whereTime('add_time', 'week')->cache(30)->sum("balance");
		$month_scores1=db("log_agent_score")->where($where1)->whereTime('add_time', 'month')->cache(30)->sum("balance");
		$last_month_scores1=db("log_agent_score")->where($where1)->whereTime('add_time', 'last month')->cache(30)->sum("balance");
	   	$total_scores1=db("log_agent_score")->where($where1)->cache(30)->sum("balance");
//	   	$this->assign("today_scores",$today_scores?$today_scores:0);
//	   	$this->assign("week_scores",$week_scores?$week_scores:0);
//	   	$this->assign("month_scores",$month_scores?$month_scores:0);
//		$this->assign("total_scores",$total_scores?$total_scores:0);
		$this->assign("today_scores1",$today_scores1?$today_scores1:0);
	   	$this->assign("week_scores1",$week_scores1?$week_scores1:0);
		$this->assign("month_scores1",$month_scores1?$month_scores1:0);
		$this->assign("last_month_scores1",$last_month_scores1?$last_month_scores1:0);
		$this->assign("total_scores1",$total_scores1?$total_scores1:0);
		
		$cz_where['a.order_type'] = 8;
		$cz_where['a.state'] = 2;
		//$cz_where['a.tj_agent_id'] = session("agent_id");
		$today_total_cz = db('log_paylog')
							->alias('a')
							->field('sum(a.balance) as balance')
							->join('info_user b','a.uid = b.id','LEFT')	
							->where($cz_where)
							->whereTime('a.add_time', 'today')
							->select();	
								
		$week_total_cz = db('log_paylog')
							->alias('a')
							->field('sum(a.balance) as balance')
							->join('info_user b','a.uid = b.id','LEFT')		
							->where($cz_where)
							->whereTime('a.add_time', 'week')
							->select();		
		
		$month_total_cz = db('log_paylog')
							->alias('a')
							->field('sum(a.balance) as balance')
							->join('info_user b','a.uid = b.id','LEFT')		
							->where($cz_where)
							->whereTime('a.add_time', 'month')
							->select();	
		
		$last_month_total_cz = db('log_paylog')
							->alias('a')
							->field('sum(a.balance) as balance')
							->join('info_user b','a.uid = b.id','LEFT')		
							->where($cz_where)
							->whereTime('a.add_time', 'last month')
							->select();	
							
		$all_total_cz = db('log_paylog')
							->alias('a')
							->field('sum(a.balance) as balance')
							->join('info_user b','a.uid = b.id','LEFT')		
							->where($cz_where)
							->select();						
		
		$cz_info['today_total_cz'] 	= $today_total_cz[0]['balance'];
		$cz_info['week_total_cz'] 	= $week_total_cz[0]['balance'];
		$cz_info['month_total_cz'] 	= $month_total_cz[0]['balance'];
		$cz_info['last_month_total_cz'] 	= $last_month_total_cz[0]['balance'];
		$cz_info['all_total_cz'] 	= $all_total_cz[0]['balance'];
		$this->assign("cz_info",$cz_info);
		$this->assign("data",$data);
    	return $this->fetch();
    }

	//市级代理商运营中心
	public function agency_record(){
		$user_level=session("user_level");
		if($user_level==1){//倍券
			$map['oem_id']=session('d_id');
			$where['a.oem_id']=session('d_id');
			$map_key['oem_id']=session('d_id');
		}
		if($user_level==4){//省代理
			$map['agency_id']=session('d_id');
			$sc['agency_id']=$map['agency_id'];
			$oem['province_id']=$map['agency_id'];
			$where['a.province_id']=$map['agency_id'];
            $map_province['province_id']=$map['agency_id'];
			$province=db("info_oem")->where($map_province)->field("id")->select();
			$province_arr=array();
			foreach($province as $val){
				$province_arr[]=$val['id'];
			}
			$province=implode(',',$province_arr);
			$map_key['agency_id1']=['in',$province];
		}
		$where['a.user_level']=2;
		$sc['is_pt1']=1;
		$oem['user_level']=3;
		$order = 'h.num desc';

	
		$citynum = db('info_oem')->field('agency_id,count(id) as citynum')->where($oem)->group('agency_id')->buildSql();//区域运营商
		$scnum = db('info_user')->field('agency_id1,count(id) as scnum')->where($sc)->group('agency_id1')->buildSql();//市场专员数
		$agentnum = db('info_agent')->field('agency_id1,count(id) as agentnum')->where($map)->group('agency_id1')->buildSql();//商户数
		$usernum = db('info_user')->field('agency_id1,count(id) as usernum')->where($map)->group('agency_id1')->buildSql();//会员数
		
		$cznum = db("log_paylog_copy")->field("agency_id1,sum(balance) as cznum")->where($map_key)->where('order_type',8)->group('agency_id1')->buildSql();
		$zsnum = db("log_paylog_copy")->field("agency_id1,sum(score) as zsnum")->where($map_key)->where('payment_type',1)->group('agency_id1')->buildSql();
		$dknum = db("log_paylog_copy")->field("agency_id1,sum(score) as dknum")->where($map_key)->where('payment_type',2)->group('agency_id1')->buildSql();
//		$map['order_type']=['in',[1,2]];
		$znum = db("log_paylog_copy")->field("agency_id1,sum(balance) as znum,count(id) as num")->where($map_key)->group('agency_id1')->buildSql();
					
    	$list = db('info_oem')->alias('a')
			->join($citynum.'b','a.id = b.agency_id','LEFT')
			->join($agentnum.'c','a.id = c.agency_id1','LEFT')
			->join($usernum.'d','a.id = d.agency_id1','LEFT')
			->join($cznum.'e','a.id = e.agency_id1','LEFT')
			->join($zsnum.'f','a.id = f.agency_id1','LEFT')
			->join($dknum.'g','a.id = g.agency_id1','LEFT')
			->join($znum.'h','a.id = h.agency_id1','LEFT')
			->join($scnum.'i','a.id = i.agency_id1','LEFT')
		    ->field('a.id,a.add_time,a.user_name,b.citynum,c.agentnum,d.usernum,e.cznum,f.zsnum,g.dknum,h.znum,h.num,i.scnum')
		    ->where($where)
			->order($order)
		    ->select();
        $this->assign('list',$list);
		$this->assign('empty','<span class="empty">没有数据</span>');
    	return $this->fetch();		
	}
	
	//区域运营商
	public function city_record(){
		$user_level=session("user_level");
		if($user_level==1){//oem
			$map['oem_id']=session('d_id');
			$where['a.oem_id']=session('d_id');
			$where['a.user_level']=3;
			$map_key['oem_id']=session('d_id');
		}
		if($user_level==2){//市代理
			$map['agency_id1']=session('d_id');
			$where['a.agency_id']=session('d_id');
			$map_key['agency_id1']=session('d_id');
		}
		if($user_level==4){
			$map['agency_id']=session('d_id');
			$sc['agency_id']=$map['agency_id'];
            $map_province['province_id']=$map['agency_id'];
			$province=db("info_oem")->where($map_province)->field("id")->select();
			$province_arr=array();
			foreach($province as $val){
				$province_arr[]=$val['id'];
			}
			$province=implode(',',$province_arr);
			$map_key['agency_id1']=['in',$province];
		}
		$where['a.user_level']=3;
		$sc['is_pt1']=1;
		$scnum = db('info_user')->field('agency_id2,count(id) as scnum')->where($sc)->group('agency_id2')->buildSql();//市场专员数
		$agentnum = db('info_agent')->field('agency_id2,count(id) as agentnum')->where($map)->group('agency_id2')->buildSql();//商户数
		$usernum = db('info_user')->field('agency_id2,count(id) as usernum')->where($map)->group('agency_id2')->buildSql();//会员数
		$cznum = db("log_paylog_copy")->field("agency_id2,sum(balance) as cznum")->where($map_key)->where('order_type',8)->group('agency_id2')->buildSql();
		$zsnum = db("log_paylog_copy")->field("agency_id2,sum(score) as zsnum")->where($map_key)->where('payment_type',1)->group('agency_id2')->buildSql();
		$dknum = db("log_paylog_copy")->field("agency_id2,sum(score) as dknum")->where($map_key)->where('payment_type',2)->group('agency_id2')->buildSql();
		$znum = db("log_paylog_copy")->field("agency_id2,sum(balance) as znum,count(id) as num")->where($map_key)->group('agency_id2')->buildSql();
						
		$list = db('info_oem')->alias('a')
			->join($scnum.'b','a.id = b.agency_id2','LEFT')
			->join($agentnum.'c','a.id = c.agency_id2','LEFT')
			->join($usernum.'d','a.id = d.agency_id2','LEFT')
			->join($cznum.'e','a.id = e.agency_id2','LEFT')
			->join($zsnum.'f','a.id = f.agency_id2','LEFT')
			->join($dknum.'g','a.id = g.agency_id2','LEFT')
			->join($znum.'h','a.id = h.agency_id2','LEFT')
		    ->field('a.id,a.add_time,a.user_name,b.scnum,c.agentnum,d.usernum,e.cznum,f.zsnum,g.dknum,h.znum,h.num')
		    ->where($where)
			->order('h.num desc')
		    ->select();
        $this->assign('list',$list);
		$this->assign('empty','<span class="empty">没有数据</span>');
    	return $this->fetch();		
	}

	//市场专员
	public function sc_record(){
		$user_level=session("user_level");
		if($user_level==1){//oem
			$map['oem_id']=session('d_id');
			$where['a.oem_id']=session('d_id');
		}
		if($user_level==2){//市代理
			$map['agency_id1']=session('d_id');
			$where['a.agency_id1']=session('d_id');
		}
		if($user_level==2){//市代理
			$map['agency_id2']=session('d_id');
			$where['a.agency_id2']=session('d_id');
		}
		if($user_level==4){
			$map['agency_id']=session('d_id');
			$where['a.agency_id']=session('d_id');
		}
		$where['is_pt1']=1;
		$agentnum = db('info_agent')->field('sc_id,count(id) as agentnum')->where($map)->group('sc_id')->buildSql();//商户数
		$usernum = db('info_user')->field('agency_id2,count(id) as usernum')->where($map)->group('agency_id2')->buildSql();//会员数
		$cznum = db("log_paylog_copy")->field("agency_id2,sum(balance) as cznum")->where($map)->where('order_type',8)->group('agency_id2')->buildSql();
		$zsnum = db("log_paylog_copy")->field("agency_id2,sum(score) as zsnum")->where($map)->where('payment_type',1)->group('agency_id2')->buildSql();
		$dknum = db("log_paylog_copy")->field("agency_id2,sum(score) as dknum")->where($map)->where('payment_type',2)->group('agency_id2')->buildSql();
		$znum = db("log_paylog_copy")->field("agency_id2,sum(balance) as znum,count(id) as num")->where($map)->group('agency_id2')->buildSql();
						
		$list = db('info_user')->alias('a')
			->join($agentnum.'c','a.id = c.sc_id','LEFT')
			->join($usernum.'d','a.id = d.agency_id2','LEFT')
			->join($cznum.'e','a.id = e.agency_id2','LEFT')
			->join($zsnum.'f','a.id = f.agency_id2','LEFT')
			->join($dknum.'g','a.id = g.agency_id2','LEFT')
			->join($znum.'h','a.id = h.agency_id2','LEFT')
		    ->field('a.id,a.add_time,a.user_name,b.scnum,c.agentnum,d.usernum,e.cznum,f.zsnum,g.dknum,h.znum,h.num')
		    ->where($where)
			->order('h.num desc')
		    ->select();
        $this->assign('list',$list);
		$this->assign('empty','<span class="empty">没有数据</span>');
    	return $this->fetch();		
	}

	//商家
	public function agent_record(){
		$user_level=session("user_level");
		if($user_level==1){//倍券
			$where['oem_id']=session('d_id');
			$map['oem_id']=session('d_id');
		}
		if($user_level==2){//市代理
			$where['agency_id1']=session('d_id');
			$map['agency_id1']=session('d_id');
		}
		if($user_level==3){//区域运营商
			$where['agency_id2']=session('d_id');
			$map['agency_id2']=session('d_id');
		}
		if($user_level==4){//省代理
			$where['agency_id']=session('d_id');
			$map['agency_id']=session('d_id');
		}	
        $cznum = db("log_paylog_copy")->field("tj_agent_id,sum(balance) as cznum")->where($map)->where('order_type',8)->group('tj_agent_id')->buildSql();
		$zsnum=db("log_paylog_copy")->field("agent_id,sum(score) as zsnum")->where($map)->where('payment_type',1)->group('agent_id')->buildSql();
		$dknum=db("log_paylog_copy")->field("agent_id,sum(score) as dknum")->where($map)->where('payment_type',2)->group('agent_id')->buildSql();
		$znum = db("log_paylog_copy")->field("agent_id,sum(balance) as znum,count(id) as num")->where($map)->group('agent_id')->buildSql();
		
    	$list = db('info_agent')->alias('a')
			->join($zsnum.'b','a.id = b.agent_id','LEFT')
			->join($dknum.'c','a.id = c.agent_id','LEFT')
			->join($znum.'h','a.id = h.agent_id','LEFT')
			->join($cznum.'e','a.id = e.tj_agent_id','LEFT')
		    ->field('a.id,a.agent_name,b.zsnum,c.dknum,e.cznum,h.znum,h.num')
		    ->where($where)
			->order('h.num desc')
		    ->paginate(20);
        $this->assign('list',$list);
		$this->assign('empty','<span class="empty">没有数据</span>');
    	return $this->fetch();
	}

	//会员
	public function user_record(){
		$user_level=session("user_level");
		if($user_level==1){//oem
			$where['oem_id']=session('d_id');
			$map['oem_id']=session('d_id');
		}
		if($user_level==2){//市代理
			$where['agency_id1']=session('d_id');
			$map['agency_id1']=session('d_id');
		}
		if($user_level==3){//区域代理
			$where['agency_id2']=session('d_id');
			$map['agency_id2']=session('d_id');
		}
		if($user_level==4){//省代理
			$where['agency_id']=session('d_id');
			$map['agency_id']=session('d_id');
		}		
		
		$znum = db("log_paylog_copy")->field("uid,sum(balance) as znum,count(id) as num")->where($map)->group('uid')->buildSql();
		$cznum = db("log_paylog_copy")->field("uid,sum(balance) as cznum")->where($map)->where('order_type',8)->group('uid')->buildSql();
		$zsnum=db("log_paylog_copy")->field("uid,sum(score) as zsnum")->where($map)->where('payment_type',1)->group('uid')->buildSql();
		$dknum=db("log_paylog_copy")->field("uid,sum(score) as dknum")->where($map)->where('payment_type',2)->group('uid')->buildSql();
		
    	$list = db('info_user')->alias('a')
			->join($zsnum.'b','a.id = b.uid','LEFT')
			->join($dknum.'c','a.id = c.uid','LEFT')
			->join($znum.'h','a.id = h.uid','LEFT')
			->join($cznum.'e','a.id = e.uid','LEFT')
		    ->field('a.id,a.nickname,b.zsnum,c.dknum,e.cznum,h.znum,h.num')
		    ->where($where)
			->order('h.num desc')
		    ->paginate(20);
        $this->assign('list',$list);
		$this->assign('empty','<span class="empty">没有数据</span>');
    	return $this->fetch();
	}

   	//明细查询
    public function commission()
    {
	   	if(request()->isPost()){
    		
    		$param=input('post.');
			if(!empty($param['begin_time']) && !empty($param['end_time'])){
				$where['a.add_time'] = ['between time',[$param['begin_time'],$param['end_time']]];
			}
    	}

		$where['a.oem_id'] = session('d_id');		
		$where['a.balance'] = ['<>',0];
//		$where['a.o_id'] = session('d_id');
		//$time="DATE_FORMAT(add_time,'%Y-%m-%d')";
    	$list=Db::table('log_oem_commission')->alias('a')
		    ->field('a.id,a.add_time,a.balance,a.order_type,a.message')
		    ->where($where)
			->order('a.add_time desc')
		    ->paginate(20);
        $this->assign('list',$list);
		
		$sumbalance = db('log_oem_commission')->alias('a')->where($where)->sum('a.balance');
		$this->assign('sumbalance',$sumbalance);
		$this->assign('empty','<span class="empty">没有数据</span>');
    	return $this->fetch();
    }
    
    //积分明细
    function score(){
    	//总鼓励金
    	$user_level=session("user_level");
		if($user_level==1){//oem
			$wheres['oem_id']=session('d_id');
			$map['oem_id']=session('d_id');
		}elseif($user_level==2){//省代理
			$wheres['agency_id1']=session('d_id');
			$map['agency_id']=session('d_id');
		}elseif($user_level==3){
			$wheres['agency_id2']=session('d_id');
			$map['city_id']=session('d_id');
		}
		$list=db("log_paylog_copy")->where($wheres)->field("uid,balance,order_type,score,sy_type,payment_type")->select();
		$data['glj_cz_ms']=0;//鼓励金购买
		if($list){
			foreach($list as $k=>$v){
				if($v['order_type']==8&&$v['uid']){
					$data['glj_cz_ms']+=$v['balance'];
				}
			}
		}
		$this->assign('data',$data);
	
		$param=input();
		if(!empty($param['begin_time']) && !empty($param['begin_time'])){
			$where['a.add_time'] = ['between time',[$param['begin_time'],$param['end_time']]];
		}

		$where['a.oem_id'] = session('d_id');		
		$where['a.balance'] = ['<>',0];
    	$list=Db::table('log_oem_score')->alias('a')
		    ->field('a.id,a.add_time,a.balance,a.order_type,a.message')
		    ->where($where)
			->order('a.add_time desc')
		    ->paginate(20,false,['query'=>request()->param()]);
        $this->assign('end_time',input('end_time'));
		$this->assign('begin_time',input('begin_time'));
		$this->assign('list',$list);
		$sumbalance = db('log_oem_score')->alias('a')->where($where)->sum('a.balance');
		$this->assign('sumbalance',$sumbalance);
		$this->assign('empty','<span class="empty">没有数据</span>');
    	return $this->fetch();
    	
    }
    
    //鼓励金导出
    public function detaiglj_dc(){
		if(!empty(input('begin_time')) && !empty(input('end_time'))){
			$where['a.add_time'] = ['between time',[input('begin_time'),input('end_time')]];
		}
		
		$where['a.oem_id'] = session('d_id');

		$where['a.balance'] = ['<>',0];
    	$list=Db::table('log_oem_score')->alias('a')
		    ->field('a.id,a.add_time,a.balance,a.order_type,a.message')
		    ->where($where)
			->order('a.add_time desc')
		    ->select();
		
		$str ="购买明细,金额,时间,"."\n";
        $str = iconv('utf-8','gbk',$str);
        foreach($list as $k=>$row){
        	$order_type = iconv('utf-8','gbk',$row['order_type']);
			$typename = '';
			switch ($order_type) {
				case '1':
					$typename = '订单佣金';
					break;
				case '2':
					$typename = '扫码佣金';
					break;
				case '3':
					$typename = '广告佣金';
					break;
				case '4':
					$typename = '退款佣金';
					break;
				case '5':
					$typename = '佣金转余额';
					break;
				case '6':
					$typename = '线下收银';
					break;
				case '7':
					$typename = '费率佣金';
					break;
				case '8':
					$typename = '会员转账';
					break;			
				case '9':
					$typename = '会员购买鼓励金';
					break;			
				default:
					$typename = '扫码佣金';
					break;
			}
			$typename = iconv('utf-8','gbk',$typename); 		
        	$balance = iconv('utf-8','gbk',$row['balance'].'	');
			$add_time = iconv('utf-8','gbk',$row['add_time'].'	');
			$message = iconv('utf-8','gbk',$row['message'].'	');
			$str .= $message.",".$balance.",".$add_time.","."\n"; //用引文逗号分开 
        } 

	  	$filename ='鼓励金报表.csv';   //设置文件名  
    	
        header("Content-type:text/csv"); 
        header("Content-Disposition:attachment;filename=".$filename); 
        header('Cache-Control:must-revalidate,post-check=0,pre-check=0'); 
        header('Expires:0'); 
        header('Pragma:public'); 
        echo $str; 
        exit;
	}
    
    
    public function detailed()
    {
		if(input('begin_time') && input('end_time')){
			$where['a.add_time'] = ['between time',[input('begin_time'),input('end_time')]];
		}

		$shengdname="";
		$sdname="";
		$sdlist="";
		$dplist="";
		$store_name="";
		$pay_type="";
		$order_sn="";
		$id="";

        $whe=[];  
        if(input('shengdname')){
			$whe['b.agency_id']=input('shengdname');
			$shengdname=input('shengdname');
		}

		if(input('sdname')){
			$where['a.agency_id1'] = input('sdname');
		    $sdname=input('sdname');
		}
		if(input('sdlist')){
			$where['a.agency_id2'] = input('sdlist');
			$sdlist=input('sdlist');
		}
		if(input('dplist')){
			$where['a.agent_id'] = input('dplist');
			$dplist=input('dplist');
		}
		if(input('store_name')){
			$where['a.chain_id'] = input('store_name');
			$store_name=input('store_name');
		}
		if(input('pay_type')){
			$where['a.pay_type'] = input('pay_type');
			$pay_type=input('pay_type');
		}
		if(input('order_sn')){
			$where['a.order_sn'] = input('order_sn');
			$order_sn=input('order_sn');
		}
		
		$where1 = [];
		if(input('id')){
			$where1['c.id'] = input('id');
			$id=input('id');
		}

		$this->assign('shengdname',$shengdname);
		$this->assign('sdname',$sdname);
		$this->assign('sdlist',$sdlist);
		$this->assign('dplist',$dplist);
		$this->assign('store_name',$store_name);
		$this->assign('pay_type',$pay_type);
		$this->assign('order_sn',$order_sn);
		$this->assign('id',$id);
		
		$user_level=session("user_level");
		$wt['status']=1;
		if($user_level==1){//oem
			$where['a.oem_id']=session('d_id');
			$shop_where['oem_id']=session('d_id');
		}
		if($user_level==2){//市代理
			$where['a.agency_id1']=session('d_id');
			$shop_where['agency_id1']=session('d_id');
			$wt['agency_id']=session('d_id');
		}
		if($user_level==4){//省代理
			$map_province['province_id']=session('d_id');
			$shop_where['agency_id']=session('d_id');
			$wt['province_id']=session('d_id');
			$province=db("info_oem")->where($map_province)->field("id")->select();
			$province_arr=array();
			foreach($province as $val){
				$province_arr[]=$val['id'];
			}
			$province=implode(',',$province_arr);
			$where['a.agency_id1']=['in',$province];
		}
		if($user_level==3){
			$where['a.agency_id2']=session('d_id');
			$shop_where['agency_id2']=session('d_id');
		}

		$where['a.order_type'] = ['not in','3,4,5'];	
		if(input("keyword")){
			$where["b.agent_name"]=["like","%".input("keyword")."%"];
		}
		
    	$paylog = db('log_paylog_copy')
    	->alias('a')
		->join('agent_store w','a.agent_id = w.agent_id and a.chain_id = w.id','LEFT')
		->join('info_agent b','a.agent_id = b.id','LEFT')
		->join('info_user c','a.uid = c.id','LEFT')
		->field('a.*,w.store_name,b.agent_name,c.mobile,c.id')
		->where($where)
		->where($whe)
		->where($where1)
		->order('a.add_time desc')
    	->paginate(10,false,['query'=>request()->param()]);
    	
		$this->assign('begin_time',input('begin_time'));
		$this->assign('end_time',input('end_time'));
		$this->assign('paylog',$paylog);

		//获取省代
		$info_province = db('info_oem')->where('user_level',4)->field("id,user_name")->select();
		$this->assign('info_province',$info_province);
		
		//获取市代
		$info_oem = db('info_oem')->where('user_level',2)->where($wt)->field("id,user_name")->select();
		$this->assign('info_oem',$info_oem);

		//获取区域运营商
		$city = db('info_oem')->where('user_level',3)->where($wt)->field("id,user_name")->select();
		$this->assign('city',$city);
		
		//获取店铺
		$info_agent = db('info_agent')->where($shop_where)->where('status',1)->field("id,agent_name")->select();
		$this->assign('info_agent',$info_agent);
		
		//获取总消费额
		$sumbalance = db('log_paylog_copy')->alias('a')
		->join('info_agent b','a.agent_id = b.id','LEFT')
		->where($where)->sum('a.balance');
		$this->assign('sumbalance',$sumbalance);
		
		//获取总分佣
		$commission = db('log_paylog_copy')->alias('a')
		->join('info_agent b','a.agent_id = b.id','LEFT')
		->where($where)->sum('a.oem_commission');
		
		//获取消费总金额 
		$balance = db("log_paylog_copy")->alias('a')->where($where)->sum('balance');
		//获取抵扣鼓励金总和
		$score = db("log_paylog_copy")->alias('a')->where($where)->where('member_score<0')->sum('member_score');
		$this->assign('score',$score);
		$this->assign('balance',$balance);
		$this->assign('commission',$commission);
		$this->assign('empty',"<span class='empty' style='margin-top:3%'>没有数据</span>");
    	return $this->fetch();
    }
	public function sdname()
    {
    	//获取省代
		$data = db('info_oem')->where('province_id',input('id'))->where('user_level',2)->where('status',1)->select();
		return json(["data"=>$data]);
	} 
	
    public function sdlist()
    {
    	//获取市代
		$data = db('info_oem')->where('agency_id',input('id'))->where('user_level',3)->where('status',1)->select();
		return json(["data"=>$data]);
    } 

    public function ywylist()
    {
		//获取店铺		
		$data = db('info_agent')->where('agency_id2',input('id'))->select();
		return json(["data"=>$data]);
    } 

    public function storelist()
    {
    	//获取店铺所属门店
		$data = db('agent_store')->where('agent_id',input('id'))->select();
		return json(["data"=>$data]);
    } 
    
    
    //明细导出
    public function detail_dc(){
		$param=input();
		if(input('begin_time') && input('end_time')){
			$where['a.add_time'] = ['between time',[input('begin_time'),input('end_time')]];
		}
		if(input('sdname'))$where['a.agency_id1'] = ['like','%'.input('sdname').'%'];
		if(input('sdlist'))$where['a.agency_id2'] = ['like','%'.input('sdlist').'%'];
		if(input('dplist'))$where['a.agent_id'] = ['like','%'.input('dplist').'%'];
		if(input('store_name'))$where['a.chain_id'] = ['like','%'.input('store_name').'%'];
		if(input('pay_type'))$where['a.pay_type'] = input('pay_type');
		if(input('order_sn'))$where['a.order_sn'] = ['like','%'.input('order_sn').'%'];

    	$user_level=session("user_level");
		if($user_level==1){//oem
			$where['a.oem_id']=session('d_id');
		}elseif($user_level==2){//省代理
			$where['a.agency_id1']=session('d_id');
		}elseif($user_level==3){
			$where['a.agency_id2']=session('d_id');
		}
    	
		$where['a.order_type'] = ['not in','3,4,5'];	
//		$where['a.sy_type'] = 2;
    	$paylog = db('log_paylog_copy')
    	->alias('a')
		->join('agent_store w','a.agent_id = w.agent_id and a.chain_id = w.id','LEFT')
		->join('info_agent b','a.agent_id = b.id','LEFT')
		->join('info_user c','a.uid = c.id','LEFT')
		->field('a.*,w.store_name,b.agent_name,c.mobile')
    	->where($where)
		->order('a.add_time desc')
    	->select();		

		$str ="订单号,店铺,门店,会员,支付方式,消费金额,分佣,日期,"."\n";
        $str = iconv('utf-8','gbk',$str);
        foreach($paylog as $k=>$row){
        	$order_sn = iconv('utf-8','gbk',$row['order_sn'].'	');
			$add_time = iconv('utf-8','gbk',$row['add_time'].'	');
			$agent_name = iconv('utf-8','gbk',$row['agent_name']); 
			$store_name = iconv('utf-8','gbk',$row['store_name']);
			$mobile = iconv('utf-8','gbk',$row['mobile']?$row['mobile'].'	':'扫码会员');
			$oem_mission = iconv('utf-8','gbk',$row['oem_commission']); 		
			if($row['pay_type']==1){
				$payname = '余额';
			}elseif($row['pay_type']==2) {
				$payname = '微信';
			}elseif($row['pay_type']==3) {
				$payname = '支付宝';
			}else{
				$payname = '银联';
			}
			$pay_type = iconv('utf-8','gbk',$payname); 
			$balance = iconv('utf-8','gbk','	'.$row['balance']);
			$str .= $order_sn.",".$agent_name.",".$store_name.",".$mobile.",".$pay_type.",".$balance.",".$oem_mission.",".$add_time.","."\n"; //用引文逗号分开 
        } 

	  	$filename ='明细列表.csv';   //设置文件名  
    	
        header("Content-type:text/csv"); 
        header("Content-Disposition:attachment;filename=".$filename); 
        header('Cache-Control:must-revalidate,post-check=0,pre-check=0'); 
        header('Expires:0'); 
        header('Pragma:public'); 
        echo $str; 
        exit;
	}


	//佣金报表导出
    public function details_dc(){
		if(!empty(input('begin_time')) && !empty(input('end_time'))){
			$where['a.add_time'] = ['between time',[input('begin_time'),input('end_time')]];
		}
		
		if(session('user_level')==1){
			$where['a.oem_id'] = session('d_id');
		}elseif(session('user_level')==2){
			$where['a.agency_id'] = session('d_id');
		}elseif(session('user_level')==3){
			$where['a.city_id'] = session('d_id');
		}

    	$list=Db::table('log_oem_commission')->alias('a')
		    ->field('a.id,a.add_time,a.balance,a.order_type,a.message')
		    ->where($where)
			->order('a.add_time desc')
		    ->select();
		
		$str ="类型,详情,变化金额,时间,"."\n";
        $str = iconv('utf-8','gbk',$str);
        foreach($list as $k=>$row){
        	$order_type = iconv('utf-8','gbk',$row['order_type']);
			$typename = '';
			switch ($order_type) {
				case '1':
					$typename = '订单佣金';
					break;
				case '2':
					$typename = '扫码佣金';
					break;
				case '3':
					$typename = '广告佣金';
					break;
				case '4':
					$typename = '退款佣金';
					break;
				case '5':
					$typename = '佣金转余额';
					break;
				case '6':
					$typename = '线下收银';
					break;
				case '7':
					$typename = '费率佣金';
					break;
				case '8':
					$typename = '会员转账';
					break;			
				case '9':
					$typename = '会员购买鼓励金';
					break;			
				default:
					$typename = '扫码佣金';
					break;
			}
			$typename = iconv('utf-8','gbk',$typename); 		
        	$balance = iconv('utf-8','gbk',$row['balance'].'	');
			$add_time = iconv('utf-8','gbk',$row['add_time'].'	');
			$message = iconv('utf-8','gbk',$row['message'].'	');
			$str .= $typename.",".$message.",".$balance.",".$add_time.","."\n"; //用引文逗号分开 
        } 

	  	$filename ='佣金报表.csv';   //设置文件名  
    	
        header("Content-type:text/csv"); 
        header("Content-Disposition:attachment;filename=".$filename); 
        header('Cache-Control:must-revalidate,post-check=0,pre-check=0'); 
        header('Expires:0'); 
        header('Pragma:public'); 
        echo $str; 
        exit;
	}
	

	//市代理明细查询
 	public function citydetailed()
    {		
		if(input('begin_time') && input('end_time')){
			$where['a.add_time'] = ['between time',[input('begin_time'),input('end_time')]];
		}
		if(input('dplist'))$where['a.agent_id'] = ['like','%'.input('dplist').'%'];
		if(input('store_name'))$where['a.chain_id'] = ['like','%'.input('store_name').'%'];
		if(input('pay_type'))$where['a.pay_type'] = input('pay_type');
//		if(input('state')){
//			$where['a.state'] = input('state');
//		}else{
//			$where['a.state'] = 2;
//		}
		if(input('order_sn'))$where['a.order_sn'] = ['like','%'.input('order_sn').'%'];

    	$where['a.oem_id'] = session('d_id');	
		$where['a.order_type'] = ['not in','3,4,5'];	
		$where['a.sy_type'] = 2;
    	$paylog = db('log_paylog_copy')
    	->alias('a')
		->join('agent_store w','a.agent_id = w.agent_id and a.chain_id = w.id','LEFT')
		->join('info_agent b','a.agent_id = b.id','LEFT')
		->join('info_user c','a.uid = c.id','LEFT')
		->field('a.*,w.store_name,b.agent_name,c.mobile')
    	->where($where)
		->order('a.add_time desc')
    	->paginate(10,false,['query'=>request()->param()]);
		$this->assign('paylog',$paylog);
		
		//获取店铺
		$info_agent = db('info_agent')->where('agency_id2',session('d_id'))->where('status',1)->select();
		$this->assign('info_agent',$info_agent);
		
		//获取业务员
		$sale_list = db('info_salesman')->where('agency_id2',session('d_id'))->select();
		$this->assign('sale_list',$sale_list);
		
		//获取总消费额
		$sumbalance = db('log_paylog')->alias('a')->where($where)->sum('a.balance');
		$this->assign('sumbalance',$sumbalance);
		
		//获取总分佣
		$commission = db('log_paylog')->alias('a')->where($where)->sum('a.agency_id2_commission');
		$this->assign('commission',$commission);
		$this->assign('empty','<span class="empty">没有数据</span>');
    	return $this->fetch();
    }

	//根据业务员获取商家
    public function salemanlist()
    {
    	//获取店铺所属门店
		$data = db('info_agent')->where('salesman_id',input('id'))->select();
		return json(["data"=>$data]);
    } 
	
	//明细导出
    public function citydetail_dc(){
		if(input('begin_time') && input('end_time')){
			$where['a.add_time'] = ['between time',[input('begin_time'),input('end_time')]];
		}
		if(input('dplist'))$where['a.agent_id'] = ['like','%'.input('dplist').'%'];
		if(input('store_name'))$where['a.chain_id'] = ['like','%'.input('store_name').'%'];
		if(input('pay_type'))$where['a.pay_type'] = input('pay_type');
		if(input('state')){
			$where['a.state'] = input('state');
		}else{
			$where['a.state'] = 2;
		}
		if(input('order_sn'))$where['a.order_sn'] = ['like','%'.input('order_sn').'%'];

    	$where['a.agency_id2'] = session('d_id');	
		$where['a.order_type'] = ['not in','3,4,5'];	
		$where['a.sy_type'] = 2;		
    	$list = db('log_paylog')
    	->alias('a')
		->join('agent_store w','a.agent_id = w.agent_id and a.chain_id = w.id','LEFT')
		->join('info_agent b','a.agent_id = b.id','LEFT')
		->field('a.*,w.store_name,b.agent_name')
    	->where($where)
		->order('a.add_time desc')
    	->select();

		$str ="订单号,店铺,门店,支付方式,消费金额,分佣,日期,"."\n";
        $str = iconv('utf-8','gbk',$str);
        foreach($list as $k=>$row){
        	$order_sn = iconv('utf-8','gbk',$row['order_sn'].'	');
			$agent_name = iconv('utf-8','gbk',$row['agent_name'].'	');
			$add_time = iconv('utf-8','gbk',$row['add_time'].'	');
			$store_name = iconv('utf-8','gbk',$row['store_name']); 		
			if($row['pay_type']==1){
				$payname = '余额';
			}elseif($row['pay_type']==2) {
				$payname = '微信';
			}elseif($row['pay_type']==3) {
				$payname = '支付宝';
			}else{
				$payname = '银联';
			}
			$pay_type = iconv('utf-8','gbk',$payname); 			
			$balance = iconv('utf-8','gbk','	'.$row['balance']);
			$commission = iconv('utf-8','gbk',$row['agency_id2_commission']); 	
			$str .= $order_sn.",".$agent_name.",".$store_name.",".$pay_type.",".$balance.",".$commission.",".$add_time.","."\n"; //用引文逗号分开 
        } 

	  	$filename ='明细列表.csv';   //设置文件名  
    	
        header("Content-type:text/csv"); 
        header("Content-Disposition:attachment;filename=".$filename); 
        header('Cache-Control:must-revalidate,post-check=0,pre-check=0'); 
        header('Expires:0'); 
        header('Pragma:public'); 
        echo $str; 
        exit;
	}

	//商家列表年审
    public function agent_limited()
    {
    	
		if(input('mobile') && input('mobile')>0){
			$where['a.mobile'] = ['like','%'.input('mobile').'%'];
		}
		
		if(input('agent_name') && input('agent_name')>0){
			$where['a.agent_name'] = ['like','%'.input('agent_name').'%'];
		}
		
		if(input('is_state') && input('is_state')>0){
			$where['a.is_state'] = input('is_state');
		}
		
		$shagent = Db::table('info_agent')->field("datediff(effective_time,now()) as jgtime,id")
		->where('datediff(effective_time,now())<=10')->buildSql();
    	
    	$where['a.id'] = ['>',0];
		$where['a.status'] = 1;	
    	$list=Db::table('info_agent a')->
		join("info_oem b","a.agency_id2=b.id",'LEFT')->
		join("info_oem c","a.agency_id1=c.id",'LEFT')->
		join($shagent." d","a.id=d.id",'inner')		
    	->field("a.*,d.jgtime,b.user_name as pname,c.user_name as cname")
    	->order('add_time desc')
		->where($where)
    	->paginate(20,false,['query'=>request()->param()]);
		$this->assign('empty','<span class="empty">没有数据</span>');
    	$this->assign('list',$list);
    	$this->assign('agent_name',input('agent_name'));
    	$this->assign('mobile',input('mobile'));
    	return $this->fetch();
    }

	//审核通过
	public function limited_pass(){
		$id=input('id');
		$where['effective_time']=date('Y-m-d H:i:s',strtotime('+1year'));
		$results=Db::name('info_agent')->where('id',$id)->update($where);

        if($results){
			return json(['code'=>200,'msg'=>'成功']);
       }else{
       		return json(['code'=>402,'msg'=>'失败']);
       }
    	
    	return $this->fetch();
    }
	
	//年审不通过冻结
	public function complain_frozen(){
		$data['status'] = 2;
	    $result=Db::table('info_agent')->where('id',$_GET['id'])->update($data);
        if($result){
			 return json(['code'=>200,'msg'=>'成功']);
       	}else{
       		return json(['code'=>402,'msg'=>'失败']);
       	}
		
		$data=Db::table('info_oem')->where('user_type=1 and user_level=3')->select();
    	$this->assign('data',$data);
    	return $this->fetch();
    }
	
	//商家银行资质审核
    public function agent_bankinfo()
    {
		if(input('mobile') && input('mobile')>0){
			$where['a.mobile'] = ['like','%'.input('mobile').'%'];
		}
		
		if(input('agent_name')){
			$where['b.agent_name1'] = ['like','%'.input('agent_name').'%'];
		}
		
		if(input('state') && input('state')>0){
			$where['b.state'] = input('state');
		}else{
			$where['b.state'] = ['<>',1];
		}
		
		//$where['a.status'] = 1;				
		$list=Db::table('info_agent')
    	->alias('a')
    	->join('agent_qianyue b','a.id = b.agent_id')
    	->field('b.agent_name1 as agent_name,b.contacts as contacts,b.state as state,b.add_time as add_time,a.id as id,b.id as sid,a.mobile')
		->order('b.add_time desc')
		->where($where)
		->paginate(20,false,['query'=>request()->param()]);
    	$this->assign('list',$list);
    	$this->assign('mobile',input('mobile'));
    	$this->assign('agent_name',input('agent_name'));
    	return $this->fetch();
    }
	
	//审核通过
	public function examine_pass(){
		$id=input('id');
		//商家资质审批通过 4 初审通过
//		$results=Db::name('info_agent')->where('id',$id)->update(["is_state"=>1]);
		$results = db("agent_qianyue")->where("agent_id",$id)->update(["state"=>4]);

        if($results){
    		//获取商家信息
    		$agent_info = Db::name('info_agent')->where('id',$id)->find();
			//短信开关 1 开  0 关
			if(config('sms_flag')==1){
	        	//发送短信提醒财务
	        	$tem_w['title']='审核成功';
				$tem=db("sms_template")->where($tem_w)->find();
				$msg=sendsms($tem['sign_name'],config('send_cwmobile'),$tem['tid'],'code',$agent_info['mobile']."签约资料已通过初审",config('cut_oem_id'));
			}
			return json(['code'=>200,'msg'=>'审核成功']);
       }else{
       		return json(['code'=>402,'msg'=>'审核失败']);
       }
    	
    	return $this->fetch();
    }
	
	//审核驳回
	public function agent_reject(){
		$this->assign('id',input('id'));
    	return $this->fetch();
    }
	
	//审核驳回
	public function examine_reject(){
		$id=input('id');
		//驳回 银行资质
		$where['is_state']=3;
		$result=Db::name('info_agent')->where('id',$id)->update($where);
		$update['state']=3;
		$update['reason']=input('content');
		$results=db("agent_qianyue")->where("agent_id",$id)->update($update);
        if($results){
        	//短信开关 1 开  0 关
			if(config('sms_flag')==1){
	    		//获取商家信息
	    		$agent_info = Db::name('info_agent')->where('id',$id)->find();
	    		//获取商家服务商信息
	    		$city_info = Db::name('info_oem')->where('id',$agent_info['agency_id2'])->find();
				
				//发送短信提醒商家
	        	$tem_w['title']='审核失败';
				$tem=db("sms_template")->where($tem_w)->find();
				$msg=sendsms($tem['sign_name'],$agent_info['mobile'],$tem['tid'],'code','商家',config('cut_oem_id'));
				    	
	        	//发送短信提醒服务商
		        $tem_w['title']='审核失败';
				$tem=db("sms_template")->where($tem_w)->find();
				$msg=sendsms($tem['sign_name'],$city_info['mobile'],$tem['tid'],'code',$city_info['user_name']."：".$agent_info['mobile']."签约资料未审核通过",config('cut_oem_id'));			
			}
			return json(['code'=>200,'msg'=>'操作成功']);
       	}else{
       		return json(['code'=>402,'msg'=>'操作失败']);
       	}
    	return $this->fetch();
    }
    
	//  电子优惠劵报表
	public function coupons(){
		if(input('begin_time') && input('end_time')){
			$where['a.add_time'] = ['between time',[input('begin_time'),input('end_time')]];
		}
		
		$user_level=session("user_level");
		if($user_level==1){//倍券
			$wheres['oem_id']=session('d_id');
			$where['a.oem_id']=session('d_id');
			$field="oem_commission";
			$sel_agent['oem_id'] = session('d_id');
		}
		if($user_level==2){//市代理
			$wheres['agency_id']=session('d_id');
			$where['a.agency_id1']=session('d_id');
			$field="agency_id1_commission";
			$sel_agent['agency_id1'] = session('d_id');
		}
		if($user_level==3){//区域运营商
			$wheres['agency_id2']=session('d_id');
			$where['a.agency_id2']=session('d_id');
			$field="agency_id2_commission";
			$sel_agent['agency_id2'] = session('d_id');
		}
		if($user_level==4){//省代理
			$wheres['province_id']=session('d_id');
			$province=db("info_oem")->where($wheres)->field("id")->select();
			$province_arr=array();
			foreach($province as $val){
				$province_arr[]=$val['id'];
			}
			$province=implode(',',$province_arr);
			$where['a.agency_id1']=['in',$province];
			$field="agency_id1_commission";
			$sel_agent['agency_id'] = session('d_id');
		}
		
		//商家名称查询
		if(input('agent_id')){
			$this->assign('agent_id',input('agent_id'));
			$where['a.tj_agent_id'] = input('agent_id');
			$field = 'tj_agent_commission';
		}else{
			$this->assign('agent_id','');
		}
		
		
        $whe=[];
		//省级代理商
		if(input('province')){
			$this->assign('agency_id',input('province'));
			$str['province_id'] = input('province');
			$province_str=db("info_oem")->where($str)->field("id")->select();
			$province_arr=array();
			foreach($province_str as $val){
				$province_arr[]=$val['id'];
			}
			$province_str=implode(',',$province_arr);
			$where['a.agency_id1']=['in',$province_str];
			$whe['d.agency_id']=input('province');
			$field = 'agency_id1_commission';
		}else{
			$this->assign('agency_id',0);
		}

		//市级代理商
		if(input('operator')){
			$this->assign('agency_id1',input('operator'));
			$where['a.agency_id1'] = input('operator');
			$field = 'agency_id1_commission';
		}else{
			$this->assign('agency_id1',0);
		}
		
		
		//区域运营商
		if(input('ch_city')){
			$this->assign('ch_city',input('ch_city'));
			$where['a.agency_id2'] = input('ch_city');
			$field = 'agency_id2_commission';
		}else{
			$this->assign('ch_city','');
		}

		//市场专员id
		if(input('pt1_id')){
			$this->assign('pt1_id',input('pt1_id'));
			$where['a.salesman_id'] = input('pt1_id');
		}else{
			$this->assign('pt1_id','');
		}

      	//会员id
		if(input('uid')){
			$this->assign('uid',input('uid'));
			$where['a.uid'] = input('uid');
		}else{
			$this->assign('uid','');
		}
		
		if($user_level==1){
			//获取市代理商列表
			// $res['province'] = array('neq',0);
			$province = db('info_oem')->field('id,user_name')->where('user_level',4)->select();
			
			$this->assign('province',$province);
			
		}
		if($user_level==1 || $user_level==4){
			//获取市代理商列表
			// $res['province'] = array('neq',0);
			$agency = db('info_oem')->field('id,user_name')->where($wheres)->where('user_level',2)->select();
			$this->assign('agency',$agency);
		}
		if($user_level==1 || $user_level==4 || $user_level==2){
			//获取区域运营商列表
			// $wheres['city'] = array('neq',0);
			$city = db('info_oem')->field('id,user_name')->where($wheres)->where('user_level',3)->select();
			$this->assign('city',$city);
		}
		
		//商家列表
		$agent_list = db('info_agent')->field('id,agent_name')->where($sel_agent)->select();
		$this->assign('agent_list',$agent_list);
    	
		
		$where['a.order_type']= 8; //购买电子劵
    	$paylog = db('log_paylog_copy')
    	->alias('a')
    	->field('a.*,w.store_name,c.goods_name,d.agent_name')
		->join('agent_store w','a.agent_id = w.agent_id and a.chain_id = w.id','left')
		->join('agent_goods c','a.goods_id = c.id','left')
		->join('info_agent d','a.agent_id = d.id','left')
		// ->where($whe)
    	->where($where)
		->order('a.add_time desc')
    	->paginate(10,false,['query'=>request()->param()]);
    	
		$this->assign('paylog',$paylog);
		$this->assign('end_time',input('end_time'));
		$this->assign('begin_time',input('begin_time'));

		//赠送笔数
		$gibe = db('log_paylog_copy')->alias('a')
				->join('info_agent d','a.agent_id = d.id','left')
				->where($where)->where($whe)->where(['payment_type' => 1])
				->count();
		$this->assign('gibe',$gibe);
		
		//抵扣笔数
		$deductible = db('log_paylog_copy')->alias('a')
					->join('info_agent d','a.agent_id = d.id','left')
					->where($where)->where($whe)->where(['payment_type' =>2])
					->count();
		$this->assign('deductible',$deductible);
		
		
		//计算鼓励金分佣
		$count_commission = db('log_paylog_copy')->alias('a')
							->join('info_agent d','a.agent_id = d.id','left')
							->where($where)->where($whe)->sum($field);	

		$this->assign('count_commission',$count_commission);
		
		//计算总分佣
		$zfy = db('log_paylog_copy')->alias('a')
		       ->where($where)
		       ->field("sum(tj_agent_commission) as sj,sum(level1_commisssion) as tj,sum(oem_commission) as oemfy,sum(agency_id1_commission) as sd,sum(agency_id2_commission) as sd2,sum(clerk_commission) as yg,sum(balance) as je")
			   ->select();
		$this->assign('fy',$zfy[0]);
		$this->assign('empty',"<span class='empty' style='margin-top:5%'>没有数据</span>");
		return $this->fetch();
	}
	
	//导出
	public function buy_export(){
		if(input('begin_time') && input('end_time')){
			$where['a.add_time'] = ['between time',[input('begin_time'),input('end_time')]];
		}
		
   		$user_level=session("user_level");
		if($user_level==1){//oem
			$wheres['oem_id']=session('d_id');
			$where['a.oem_id']=session('d_id');
			
			$str ="订单号,会员编号,电子劵面额,平台分佣,省级代理商分佣,市级代理商分佣,区域运营商分佣,市场专员分佣,商家分佣,员工分佣,推荐人分佣,日期"."\n";
		}
		if($user_level==4){//省代理
			$wheres['agency_id1']=session('d_id');
			$where['a.agency_id1']=session('d_id');
			
			$str ="订单号,会员编号,电子劵面额,省级代理商分佣,市级代理商分佣,区域运营商分佣,市场专员分佣,商家分佣,员工分佣,推荐人分佣,日期"."\n";
		}
		if($user_level==2){//省代理
			$wheres['agency_id1']=session('d_id');
			$where['a.agency_id1']=session('d_id');
			
			$str ="订单号,会员编号,电子劵面额,市级代理商分佣,区域运营商分佣,市场专员分佣,商家分佣,员工分佣,推荐人分佣,日期"."\n";
		}
		if($user_level==3){
			$where['agency_id2']=session('d_id');
			$where['a.agency_id2']=session('d_id');
			
			$str ="订单号,会员编号,电子劵面额,区域运营商分佣,商家分佣,员工分佣,推荐人分佣 ,日期"."\n";
		}
		
		
		//商家名称查询
		if(input('agent_id')){ 
			$where['a.tj_agent_id'] = input('agent_id');
			$field = 'tj_agent_commission'; 
		}
	
	    //区域运营商
	    if($user_level==1 || $user_level==2 || $user_level==4){	
			if(input('ch_city')){ 
				$where['a.agency_id2'] = input('ch_city');
				$field = 'agency_id2_commission'; 
			}
		}
		if($user_level==1 || $user_level==4){	
			//市代理商
			if(input('operator')){ 
				$where['a.agency_id1'] = input('operator');
				$field = 'agency_id1_commission'; 
			}
		}
		//市场专员id
		if(input('pt1_id')){ 
			$where['a.pt1_id'] = input('pt1_id'); 
		}
		
		//会员id
		if(input('uid')){ 
			$where['a.uid'] = input('uid'); 
		}
		
		$where['a.order_type']= 8; //购买电子劵	
		
    	$list = db('log_paylog_copy')
    	->alias('a')
		->field('a.*')
    	->where($where)
		->order('a.add_time desc')
    	->select();
		
        $str = iconv('utf-8','gbk',$str);
        foreach($list as $k=>$row){
        	$order_sn = iconv('utf-8','gbk',$row['order_sn'].'	');
			$uid = iconv('utf-8','gbk',$row['uid'].'	');
			$balance = iconv('utf-8','gbk',$row['balance']*4 .'	'); 
			
			$tj_agent_commission = iconv('utf-8','gbk','	'.$row['tj_agent_commission']);
			$tj_clerk_id = iconv('utf-8','gbk','	'.$row['tj_clerk_id']);		
			$clerk_commission = iconv('utf-8','gbk','	'.$row['clerk_commission']);
			$pt_commission = iconv('utf-8','gbk','	'.$row['pt_commission']);		
			$level1_commisssion = iconv('utf-8','gbk','	'.$row['level1_commisssion']);
			$hhr_commission = iconv('utf-8','gbk',$row['pt_commission'].'');
			$add_time = iconv('utf-8','gbk','	'.$row['add_time']);
			
			
			if($user_level==1){//oem
				$oem_commission = iconv('utf-8','gbk',$row['oem_commission'].'	');	
				$agency_id1_commission = iconv('utf-8','gbk',$row['agency_id1_commission'].'	');	
				$agency_id2_commission = iconv('utf-8','gbk',$row['agency_id2_commission'].'	');	
				$a1_commission = iconv('utf-8','gbk',$row['a1_commission'].'	');	
				$a2_commission = iconv('utf-8','gbk',$row['a2_commission'].'	');																
				$str .= $order_sn.",".$uid.",".$balance.",".$oem_commission.",".$agency_id1_commission.",".$agency_id2_commission.",".$tj_agent_commission.",".$tj_clerk_id.",".$clerk_commission.",".$level1_commisssion.','.$add_time.","."\n"; //用引文逗号分开 
			}
			
			if($user_level==2){//省代理
				$agency_id1_commission = iconv('utf-8','gbk',$row['agency_id1_commission'].'	');	
				$agency_id2_commission = iconv('utf-8','gbk',$row['agency_id2_commission'].'	');	
				$str .= $order_sn.",".$uid.",".$balance.",".$agency_id1_commission.",".$agency_id2_commission.','.$tj_agent_commission.",".$tj_clerk_id.",".$clerk_commission.",".$level1_commisssion.",".$add_time.","."\n"; //用引文逗号分开 
			}
			if($user_level==3){
				$agency_id2_commission = iconv('utf-8','gbk',$row['agency_id2_commission'].'	');	
				$str .= $order_sn.",".$uid.",".$balance.",".$agency_id2_commission.','.$tj_agent_commission.",".$tj_clerk_id.",".$clerk_commission.",".$level1_commisssion.",".$add_time.","."\n"; //用引文逗号分开 
			}
			
        } 

	  	$filename ='购买电子劵列表.csv';   //设置文件名  
    	
        header("Content-type:text/csv"); 
        header("Content-Disposition:attachment;filename=".$filename); 
        header('Cache-Control:must-revalidate,post-check=0,pre-check=0'); 
        header('Expires:0'); 
        header('Pragma:public'); 
        echo $str; 
        exit;
	}
}
